package com.createImg.createImg;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("restriction")
public class ChartGraphics {
	
	String [] names = {"幼圆","微软雅黑","新宋体","楷体"};
	
	String [] content={};
	
	int    [] x={0};
	
	int    [] y={0};
	
	int imageWidth = 500;//图片的宽度
	
	int imageHeight =50+50;//图片的高度

	String fileLocation;
	
	String imgurl;
	
	BufferedImage image;
	
	public ChartGraphics(String[] names, int imageWidth, int imageHeight,
			String fileLocation, String imgurl) {
	
		super();
		this.names = names;
		this.imageWidth = imageWidth;
		this.imageHeight = imageHeight;
		this.fileLocation = fileLocation;
		this.imgurl = imgurl;
	}
	
	public static void main(String[] args) {
		String [] names = {"幼圆","微软雅黑","新宋体","楷体","华文隶书","华文行楷","华文细黑","华文琥珀","华文楷体","华文新魏","华文彩云"};
		for (int i = 0; i < 10; i++) {
			new ChartGraphics(names,400,400,"D:\\a\\img"+i+".jpg",null).graphicsGeneration();
		}
	}
	
	private void createImage() {
	
		try {
			FileOutputStream fos = new FileOutputStream(fileLocation);
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
			encoder.encode(image);
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void graphicsGeneration() {
		
		image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
		
		Graphics graphics = image.getGraphics();
		
		graphics.setColor(Color.WHITE);
		
		graphics.fillRect(0, 0, imageWidth, imageHeight);

		setFontColor(graphics, Color.green, getFont());
		
		graphics.drawString("测试文字",50 , 50);

		if(imgurl != null && imgurl.length() >0 ){
				
			BufferedImage bimg = null;
			
			try {
				
				bimg = javax.imageio.ImageIO.read(new java.io.File(imgurl));
				
			} catch (Exception e1) {
				
			    e1.printStackTrace();
			    
			}
			
			if(bimg!=null) graphics.drawImage(bimg, 0, 0,100,100,0, 0,300,300, null);
			
		}
		graphics.dispose();
		
		createImage();
	}
	
	private  void setFontColor(Graphics graphics,Color color,Font font){
		
		graphics.setColor(color);
		
		graphics.setFont(font);
		
	}
	
	private  Font getFont(){
		
		Font font = new Font ( getName() , 0 , 20 );
		
		return font;
	}
	
	private  String getName() {
		
		double f = 1d / (names.length);
		
		double d = Math.random();
		
		int i = 1;
		
		double s = f * i;
		
		for (; i <= names.length ; i++ ) {
			
			if(d <= s*i) return names[i-1];
			
		}
		
		return names[0];
	}
	
	
}
